package com.bbzn.device.client.service.emq;

import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.config.EmqCode;
import com.bbzn.device.client.constant.CwtingConstant;
import com.bbzn.device.client.dataobject.Device;
import com.bbzn.device.client.dataobject.Strategy;
import com.bbzn.device.client.dto.ct.data.GeneralPayload;
import com.bbzn.device.client.dto.ct.data.TemplateDeviceDTO;
import com.bbzn.device.client.service.*;
import com.bbzn.device.client.utils.Base64Util;
import com.bbzn.device.client.utils.MsgTemplateUtil;
import com.bbzn.device.client.utils.RedisUtils;
import com.bbzn.device.client.utils.SpringUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author wulongbo
 * @Date 2021/9/10 15:46
 * @Version 1.0
 */

@Component
@Slf4j
@Service
public class CwtingHandle {

    @Autowired
    private StrategyService strategyService;

    @Autowired
    private GroupService groupService;

    @Resource
    private DeviceService deviceService;

    @Autowired
    private PublishService publishService;

    @Autowired
    private RedisUtils redisUtil;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "routeKey", durable = "true"),
            exchange = @Exchange(name = "cwtingnbExchange",
                    durable = "true",
                    type = "topic",
                    ignoreDeclarationExceptions = "true"),
            key = "cwtingnb.*"
    ))
    @RabbitHandler
    @Transient
    public void process(Message message, Channel channel) throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.err.println("消费消息:" + message.getPayload());
        if (null == message.getPayload()) {
            Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
            channel.basicAck(deliveryTag, false);
        }
        GeneralPayload generalPayload = JSONObject.parseObject(message.getPayload().toString(), GeneralPayload.class);
        if (null == generalPayload) {
            Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
            channel.basicAck(deliveryTag, false);
            return;
        }
        String imei = generalPayload.getIMEI();
        String channelCode = generalPayload.getAlarmCode();
        //业务判断0
        if (null == channelCode) {
            return;
        }
        // 2.根据code查询具体业务实现
        Strategy strategy = new Strategy();
        strategy.setChannelCode(Long.valueOf(channelCode));
        strategy = strategyService.getStrategy(strategy);
        if (null == strategy) {
            return;
        }
        String strategyBeanId = strategy.getStrategyBeanId();
        if (null == strategyBeanId) {
            return;
        }

        int state = groupService.checkStateByImei(imei);
        if (state == 0) {
            // 使用beanid从容器获取对象
            CwtingStrategy cwtingStrategy = SpringUtils.getBean(strategyBeanId, CwtingStrategy.class);
            cwtingStrategy.dealAlarm(channelCode, imei);
        } else if (state == 1) {
            TemplateDeviceDTO info = deviceService.getInfoByImei(imei);
            if (info.getDeviceName() == null || info.getDeviceName() == "") {
                info.setDeviceName("未定义名称");
            }
            Map<String, String> replaceMap = new HashMap<String, String>();
            replaceMap.put("deviceCategoryName", info.getDeviceCategoryName());
            replaceMap.put("deviceName", info.getDeviceName());
            replaceMap.put("imei", imei);
            String data = MsgTemplateUtil.replacePlaceHolderWithMapValue(CwtingConstant.NOTIFY_TEMPLATE, replaceMap);
            publishService.sendToMqtt(data, EmqCode.sendTopic + info.getUserId() + EmqCode.endTopic, 2);

            String decodeStr = Base64Util.decode(imei + "::" + info.getUserId());
            redisUtil.setEx(decodeStr, strategyBeanId + "." + channelCode, 5, TimeUnit.MINUTES);
        }
        Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(deliveryTag, true);
    }


}
